import numpy as np
from datetime import timedelta
from qtorch.core import ReturnsDataset

class SignalValidator:
    def __init__(self, volatility_threshold=3.0, min_liquidity=1e6):
        self.volatility_threshold = volatility_threshold
        self.min_liquidity = min_liquidity
        self.last_valid_signals = {}
        
    def validate(self, signal, symbol, market_data):
        """验证信号有效性返回(bool, reason)"""
        if not self._check_volatility(symbol, market_data):
            return False, "volatility_exceeded"
        if not self._check_liquidity(market_data):
            return False, "insufficient_liquidity"
        if not self._check_time_continuity(symbol, market_data.timestamp):
            return False, "time_gap_detected"
        return True, "valid"

    def _check_volatility(self, symbol, market_data):
        returns = np.diff(np.log(market_data.close))
        current_vol = np.std(returns[-30:]) * np.sqrt(252)
        return current_vol <= self.volatility_threshold

    def _check_liquidity(self, market_data):
        return market_data.volume * market_data.close >= self.min_liquidity

    def _check_time_continuity(self, symbol, timestamp):
        last_time = self.last_valid_signals.get(symbol)
        if last_time and (timestamp - last_time) > timedelta(minutes=5):
            return False
        self.last_valid_signals[symbol] = timestamp
        return True